package com.yiya.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yiya.bean.Bill;
import com.yiya.bean.Inventory;
import com.yiya.bean.SysUser;
import com.yiya.mapper.BillMapper;
import com.yiya.mapper.InventoryMapper;
import com.yiya.model.BillCplex;
import com.yiya.model.BillCplexModel;
import com.yiya.model.InventoryExample;
import com.yiya.utils.DataTypeUtil;

@Service("billService")
public class BillService {
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(BillService.class);

	@Autowired
	private BillMapper billMapper;

	@Autowired
	private InventoryMapper inventoryMapper;

	public List<BillCplex> queryByList(BillCplexModel bean) {
		Integer rowCount = queryByCount(bean);
		bean.getPager().setRowCount(rowCount);
		List<BillCplex> bills = billMapper.selectByModel(bean);
		return bills;
	}

	public int queryByCount(BillCplexModel bean) {
		return billMapper.countByModel(bean);
	}

	/**
	 * 添加进出货明细记录
	 * 
	 * @param bill
	 * @return
	 */
	public int add(Bill bill) {
		return billMapper.insert(bill);
	}

	/**
	 * 增加库存数量
	 * 
	 * @param bill
	 */
	public void addInventory(Bill bill) {
		InventoryExample example = new InventoryExample();
		example.createCriteria().andProductIdEqualTo(bill.getProductId())
				.andRepositoryIdEqualTo(bill.getRepositoryId());
		List<Inventory> inventories = inventoryMapper.selectByExample(example);
		if (inventories == null || inventories.isEmpty()) {
			// 如果该仓库不存在该产品仓储记录
			Inventory inventory = new Inventory();
			inventory.setProductId(bill.getProductId());
			inventory.setRepositoryId(bill.getRepositoryId());
			inventory.setQuantity(bill.getQuantity());
			inventory.setPrice(bill.getPrice());
			inventoryMapper.insert(inventory);
		} else {
			// 如果该仓库已存在该产品仓储记录
			Inventory inventory = inventories.get(0);
			inventory.setQuantity(inventory.getQuantity() + bill.getQuantity());
			inventory.setPrice(bill.getPrice());
			inventoryMapper.updateByPrimaryKeySelective(inventory);
		}
	}

	/**
	 * 减少库存数量
	 * 
	 * @param bill
	 * @return 0:库存不足，出库失败；1:库存数量充足
	 */
	public int reduceInventory(Bill bill) {
		int result = 0;// 库存不足
		InventoryExample example = new InventoryExample();
		example.createCriteria().andProductIdEqualTo(bill.getProductId())
				.andRepositoryIdEqualTo(bill.getRepositoryId());
		List<Inventory> inventories = inventoryMapper.selectByExample(example);
		if (inventories != null && !inventories.isEmpty()) {
			Inventory inventory = inventories.get(0);
			if (inventory.getQuantity() >= bill.getQuantity()) {
				inventory.setQuantity(inventory.getQuantity()
						- bill.getQuantity());
				inventoryMapper.updateByPrimaryKeySelective(inventory);
				result = 1;
			}
		}
		return result;
	}

	public int Update(Bill bill) {
		int result = 0;
		if (bill.getCheckStatus() != null && bill.getCheckStatus() == 1) {
			// 如果已入库，则只能修改价格
			Bill b = new Bill();
			b.setId(bill.getId());
			b.setPrice(bill.getPrice());
			result = billMapper.updateByPrimaryKeySelective(b);
		} else {
			// 如果尚未入库，可以更改所有字段

			result = billMapper.updateByPrimaryKeySelective(bill);
		}
		return result;
	}

	public Bill queryById(Integer id) {
		return billMapper.selectByPrimaryKey(id);
	}

	public List<BillCplex> queryAllByList(BillCplexModel bean) {
		List<BillCplex> bills = billMapper.selectAllByModel(bean);
		return bills;
	}

	/**
	 * 
	 * @param list
	 * @param type
	 *            {1:含价格,2:不含价格}
	 * @return
	 */
	public HSSFWorkbook export(List<BillCplex> list, int type) {
		String[] excelHeader = { "账单编号", "产品名称", "所属仓库", "商家名称", "账单日期", "数量",
				"单价", "总额", "备注" };
		String[] excelSimpleHeader = { "账单编号", "产品名称", "所属仓库", "商家名称", "账单日期",
				"数量", "备注" };

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("出账单");
		HSSFRow row = sheet.createRow(0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		if (type == 1) {
			// 导出的excel包含价格
			for (int i = 0; i < excelHeader.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(excelHeader[i]);
				cell.setCellStyle(style);
				sheet.autoSizeColumn(i);
			}
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow(i + 1);
				BillCplex bill = list.get(i);
				row.createCell(0).setCellValue(bill.getNumber());
				row.createCell(1).setCellValue(bill.getProduct().getName());
				row.createCell(2).setCellValue(bill.getRepository().getName());
				row.createCell(3).setCellValue(bill.getMerchant().getName());
				row.createCell(4).setCellValue(
						format.format(bill.getBillDate()));
				int quantity = bill.getQuantity() == null ? 0 : bill
						.getQuantity();
				float price = bill.getPrice() == null ? 0 : bill.getPrice();
				row.createCell(5).setCellValue(quantity);
				row.createCell(6).setCellValue(DataTypeUtil.KeepDecimal(2, (double) price));
				row.createCell(7).setCellValue(
						DataTypeUtil.KeepDecimal(2,DataTypeUtil.convertFloatToDouble(quantity * price)));
				row.createCell(8).setCellValue(bill.getRemark());
			}
		} else {
			// 导出的excel不包含价格
			for (int i = 0; i < excelSimpleHeader.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(excelSimpleHeader[i]);
				cell.setCellStyle(style);
				sheet.autoSizeColumn(i);
			}
			for (int i = 0; i < list.size(); i++) {
				row = sheet.createRow(i + 1);
				BillCplex bill = list.get(i);
				row.createCell(0).setCellValue(bill.getNumber());
				row.createCell(1).setCellValue(bill.getProduct().getName());
				row.createCell(2).setCellValue(bill.getRepository().getName());
				row.createCell(3).setCellValue(bill.getMerchant().getName());
				row.createCell(4).setCellValue(
						format.format(bill.getBillDate()));
				int quantity = bill.getQuantity() == null ? 0 : bill
						.getQuantity();
				row.createCell(5).setCellValue(quantity);
				row.createCell(8).setCellValue(bill.getRemark());
			}
		}
		return wb;
	}

	public void delete(Integer[] ids, SysUser user) {
		Date nowTime = new Date();
		for (Integer id : ids) {
			Bill bill = billMapper.selectByPrimaryKey(id);
			if (bill.getCheckStatus() == null || bill.getCheckStatus() != 1) {
				bill.setUpdateBy(user.getId());
				bill.setUpdateTime(nowTime);
				bill.setDelFlag(1);
				billMapper.updateByPrimaryKeySelective(bill);
			}
		}
	}

	public int check(Integer[] ids, SysUser user) {
		int flag = 1;
		Date nowTime = new Date();
		for (Integer id : ids) {
			Bill bill = billMapper.selectByPrimaryKey(id);
			if (bill.getCheckStatus() == null || bill.getCheckStatus() != 1) {
				bill.setUpdateBy(user.getId());
				bill.setUpdateTime(nowTime);
				if (bill.getType() == 1) {
					addInventory(bill);
					bill.setCheckStatus(1);
					billMapper.updateByPrimaryKeySelective(bill);
				} else if (bill.getType() == 2) {
					int result = reduceInventory(bill);
					if (result == 1) {
						bill.setCheckStatus(1);
						billMapper.updateByPrimaryKeySelective(bill);
					} else {
						flag = 0;
					}
				}
			}
		}
		return flag;
	}

}
